<template>
  <div>
    <el-dialog :visible.sync="dialogFormVisible" :title="title">
      <el-form>
        <el-form-item :label-width="formLabelWidth" label="章节标题">
          <el-input v-model="chapter.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="章节排序">
          <el-input-number v-model="chapter.sort" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateChapter">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import chapterApi from '@/api/chapter'
export default {
  data() {
    return {
      title: '添加章节',
      chapter: {
        sort: 1
      },
      formLabelWidth: '120px',
      dialogFormVisible: false
    }
  },
  methods: {
    open(chapterId) { // 打开对话框 回显要更新章信息
      this.title = '更新章节'
      chapterApi.getById(chapterId).then(r => {
        this.chapter = r.data.item
        this.dialogFormVisible = true
      })
    },
    close() {
      // 清空缓存
      this.chapter = { sort: 1 }
      // 关闭对话框
      this.dialogFormVisible = false
    },
    saveOrUpdateChapter() {
      if (!this.chapter.id) {
        this.saveChapter()
      } else {
        this.updateChapter()
      }
    },
    updateChapter() {
      chapterApi.update(this.chapter).then(r => {
        this.$message.success('更新成功')
        this.close()
        // 刷新
        this.$parent.getChaptersAndVideos()
      })
    },
    saveChapter() {
    // 新增章
    // 除了收集章的数据还要给章设置所属的课程ID
      this.chapter.courseId = this.$parent.$parent.courseId// 当前页面是step2 index的子页面
      // 提交新增请求
      chapterApi.save(this.chapter).then(r => {
        this.$message.success('新增成功')
        this.close()
        // 刷新
        this.$parent.getChaptersAndVideos()
      })
    }
  }

}
</script>
